package Servlets;

import java.io.IOException;
import java.util.Set;
import java.util.UUID;
import java.util.Vector;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.websocket.WebSocket;
import org.eclipse.jetty.websocket.WebSocketServlet;

public class CWServlet extends WebSocketServlet
{
	
	class Point{
		
		int x,y;

		public int getX() {return x;}
		public void setX(int x) {this.x = x;}
		public int getY() {return y;}
		public void setY(int y) {this.y = y;}
		
		public void setString(String xy){
			String [] arr = xy.split("\\|");
			x = Integer.parseInt(arr[0]);
			y = Integer.parseInt(arr[1]);			
		}
		
		public String getString(){
			return Integer.toString(x) + "|" + Integer.toString(y) ;
		}
		
	}
	
	abstract class GameObject{
	
		User user;
		String id;
		Point position;
		
		public GameObject(User user){
			this.user = user;
		}
		
		public String getId(){return id;};
		public User getUser(){return user;};
		public void setUser(User user){this.user = user;};
		
		public Point getPosition(){return position;}
		public void setPosition(Point position){this.position = position;}
	}

	class User{
		
		String id, name;
		int score = 0;
		
		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public String getName() {
			return name;
		}

		public void setName(String name) {
			this.name = name;
		}

		public int getScore() {
			return score;
		}

		public void setScore(int score) {
			this.score = score;
		}

		public User(String id, String name){
			
		}
		
	}
	
	class Ship extends GameObject{

		public Ship(User user) {
			super(user);
		}
		
	}
	
	class Bullet extends GameObject{
		
		public Bullet (User user) {
			super(user);
		}
		
	}
	
	private static Vector<GameObject> gameObjects = new Vector<GameObject>();
	
	private static final long serialVersionUID = 1L;

	private final Set<ChatWebSocket>  _members = new CopyOnWriteArraySet<ChatWebSocket>();
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException ,IOException 
    {
        //getServletContext().getNamedDispatcher("default").forward(request,response);
    	response.getWriter().println("regular doGet()");
    }
    
    protected WebSocket doWebSocketConnect(HttpServletRequest request, String protocol)
    {
        return new ChatWebSocket();
    }

    
    class ChatWebSocket implements WebSocket
    {
        Outbound _outbound;
        String _name = "", id;
        Ship ship;
        
        public void onConnect(Outbound outbound)
        {
            _outbound=outbound;
            
            
            System.out.println("Connected");
            
            //Send the new connection info to all users.
            id = UUID.randomUUID().toString();
            System.out.println("uuid = " + id);
            
            
            //Send everyone the new ship
            for (ChatWebSocket member : _members){
            	try{
            		System.out.println("Sending data");
                    member._outbound.sendMessage("newship|" + id + "|0|0");
                }catch(IOException e) {Log.warn(e);}
            }
            
            //Send the current ship the info about the others
            for (ChatWebSocket member : _members){
            	try{
            		outbound.sendMessage("newship|" + member.ship.id + "|" + member.ship.getPosition().getString());
                }catch(IOException e) {Log.warn(e);}
            }
            
        }
        
        public void onMessage(byte frame, byte[] data,int offset, int length)
        {}

        public void onMessage(byte frame, String data)
        {
        	
        	System.out.println("Received: " + data);
        	
        	if(data.startsWith("shippos")){
        		for (ChatWebSocket member : _members){
                	try{
                		System.out.println("forwarding ship pos");
                        member._outbound.sendMessage("shippos|" + id + "|");
                    }catch(IOException e) {Log.warn(e);}
                }
        	}

        }

        public void onDisconnect()
        {
        	//SendConnectedUsers();
            _members.remove(this);
        }
        
        public String getName(){
        	return _name;
        }
        
        private void SendConnectedUsers(byte frame){
        	System.out.println("Sending connected users");
        	
        	StringBuilder sb = new StringBuilder();
        	sb.append("{\"type\" : \"usersList\" , \"list\":[\"\"");
        	for (ChatWebSocket member : _members){
        		sb.append(",\"" +  member.getName() + "\"");
        	}
        	sb.append("] } ");
        	
        	String names = sb.toString();
        	
        	System.out.println(names);
        	
			for (ChatWebSocket member : _members){
				try{
					member._outbound.sendMessage(names);
					//member._outbound.sendMessage(frame, names);
				}catch(IOException e) {Log.warn(e);}
			}
        }
        
        
        
    }
	
}
